/*
 * WebServer_GUIApp.java
 */
package webserver_gui;

import Controller.ClientXMLServerInfo;
import Controller.OurListener;
import Supporter.OurLogger;
import Supporter.OurSupporter;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.EventObject;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;

/**
 * The main class of the application.
 */
public class WebServer_GUIApp extends SingleFrameApplication {

    private static Thread listener;
    private WebServer_GUIView view;

    public static void stopListener() {
        listener.stop();
    }

    public static void setAndStartListener(Thread aListener) {
        listener = aListener;
        listener.start();
    }

    /**
     * At startup create and show the main frame of the application.
     */
    @Override
    protected void startup() {
        if (new File("Log").exists() == false) {
            new File("Log").mkdir();
        }

        if (OurLogger.init(new File("Log\\" + OurSupporter.getFullDateTime(new Date(System.currentTimeMillis())).replace('/', '-').replace(':', '-') + ".xml"))) {
            OurLogger.logNotError(this, "----- Started -----", Level.INFO);
            super.addExitListener(new ExitListener() {

                public boolean canExit(EventObject event) {
                    return true;
                }

                public void willExit(EventObject event) {
                    OurLogger.logNotError(this, "----- Closed -----", Level.INFO);
                    OurLogger.close();
                }
            });
        }

        try {
            int listeningPort = Integer.parseInt(ClientXMLServerInfo.GetInfo().GetPort());
            setAndStartListener(new Thread(new OurListener(listeningPort)));

            view = new WebServer_GUIView(this);
            show(view);
            LoadTrayICon();
        } catch (Exception ex) {
            OurLogger.logError(this, "startup()", ex, Level.SEVERE);
        }
    }

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     */
    @Override
    protected void configureWindow(java.awt.Window root) {
    }

    /**
     * A convenient static getter for the application instance.
     * @return the instance of WebServer_GUIApp
     */
    public static WebServer_GUIApp getApplication() {
        return Application.getInstance(WebServer_GUIApp.class);
    }

    /**
     * Main method launching the application.
     */
    public static void main(String[] args) {
        launch(WebServer_GUIApp.class, args);
    }
    boolean bShowView = true;

    private void LoadTrayICon() throws IOException {
        try {
            //Check the SystemTray is supported
            if (!SystemTray.isSupported()) {
                OurLogger.logNotError(this, "System tray is not supported!", Level.INFO);
                return;
            }

            final PopupMenu popup = new PopupMenu();
            BufferedImage myPicture = ImageIO.read(new File("Tray icon.jpg"));
            final TrayIcon trayIcon = new TrayIcon(myPicture);
            final SystemTray tray = SystemTray.getSystemTray();

            // Create a pop-up menu components
            MenuItem showItem = new MenuItem("Show");
            MenuItem aboutItem = new MenuItem("About");
            MenuItem exitItem = new MenuItem("Exit");

            //Add components to pop-up menu
            popup.add(showItem);
            popup.add(aboutItem);
            popup.add(exitItem);

            trayIcon.setPopupMenu(popup);
            trayIcon.setToolTip("HNV WebServer 1.0");
            tray.add(trayIcon);

            trayIcon.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    toggleMainFrame();
                }
            });

            aboutItem.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(null,
                            "          __ HNV WebServer __\r\n"
                            + "           version 1.0.0\r\n\r\n"
                            + "    Chương trình được thực hiện bởi\r\n"
                            + "  Hùng, Nguyên, Vương lớp 10HCB\r\n"
                            + "     trường ĐH Khoa Học Tự Nhiên TpHCM");

                }
            });

            exitItem.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    tray.remove(trayIcon);
                    System.exit(0);
                }
            });

            showItem.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    bShowView = false;
                    toggleMainFrame();
                }
            });
        } catch (Exception e) {
            OurLogger.logError(this, "LoadTrayICon", e, Level.WARNING);
        }
    }

    public void toggleMainFrame() {
        if (bShowView) {
            hide(view);
            bShowView = false;
        } else {
            show(view);

            getMainFrame().setVisible(true);
            getMainFrame().setExtendedState(JFrame.MAXIMIZED_BOTH);
            bShowView = true;
        }
    }
}
